package com.gongqi.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;


import com.gongqi.gift.clients.LoginUserClient;
import com.gongqi.gift.domain.Employee;
import com.gongqi.gift.domain.LoginUser;
import com.gongqi.gift.domain.Tenant;
import com.gongqi.gift.dto.TenantEnterDto;

import com.gongqi.gift.exception.asserts.Assert;
import com.gongqi.gift.exception.code.StatusCode;
import com.gongqi.gift.mapper.EmployeeMapper;
import com.gongqi.gift.mapper.TenantMapper;
import com.gongqi.gift.query.TenantQuery;
import com.gongqi.gift.service.IEmployeeService;
import com.gongqi.gift.service.ITenantService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gongqi.gift.util.AjaxResult;
import com.gongqi.gift.util.PageList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gongqi
 * @since 2022-10-09
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private LoginUserClient loginUserClient;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private TenantMapper tenantMapper;
    @Override
    public PageList<Tenant> selectPAgeList(TenantQuery query) {
        Page<Tenant> page = new Page<>(query.getPage(),query.getRows());//分页条件
        List<Tenant> rows = tenantMapper.selectPageList(page,query);//查询后，总数会放到page中，返回当前页数据。
        return new PageList<>(page.getTotal(),rows);
    }

    @Override
    public AjaxResult settlement(TenantEnterDto enteringDto) {

        Employee admin = enteringDto.getAdmin();
        Tenant tenant = enteringDto.getTenant();
        Long mealId = enteringDto.getMealId();
        //1参数校验
        //1.1 null校验
        //1.2 店铺是否存在校验
        //1.3 店铺管理员校验
        validate(enteringDto);
        //2 保存数据  店铺 店铺管理员 登陆信息  用户套餐中间表
        //2.1 保存登陆信息及用户套餐中间表并发返回loginId-->其他服务的功能（openfegin） loginUser+mealId=Map/Dto
        //方案1：谁提供服务谁写 好处：能直接用它的公共代码,坏处就是要让别人写接口---一个团队甚至一个人
        //方案2：更加接口文档自己来写  好处：没有任何耦合，坏处：有重复dto----如果两个团队分别写服务
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(admin, loginUser);
        loginUser.setType(0);//登录用户类型为管理员
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
        if (!ajaxResult.isSuccess()){
            return AjaxResult.me().setSuccess(false).setMessage(ajaxResult.getMessage());
        }

        //2.2保存店铺管理员
        admin.setType(5);//机构管理员
        //这里登录用户返回的自增id在另一个模块，这里拿不到,所以登录用户id存到resultObj里面，
        //存的时候是Long,通过Object转换，拿出来就是Integer了
        Long loginId = Long.valueOf(((Integer) ajaxResult.getResultObj()).longValue());
        admin.setLoginId(loginId);
        employeeMapper.insert(admin);

        //2.3保存店铺
        tenant.setState(0);//待审核
        tenant.setAdminId(admin.getId());
        tenantMapper.insert(tenant);

        //2.4保存用户套餐中间表
        Long tenantId = tenant.getId();
        Map<String,Object> map = new HashMap<>();
        map.put("mealId",mealId);
        map.put("tenantId",tenantId);
        map.put("state", 0);//未支付
        tenantMapper.insertTenantMeal(map);
        return AjaxResult.me();

    }
    private void validate(TenantEnterDto tenantEnterDto) {
        //1参数校验
        //1.1 null校验
        Employee admin = tenantEnterDto.getAdmin();
        Tenant tenant = tenantEnterDto.getTenant();


        //两次密码比对
        Assert.assertEquals(admin.getPassword(),admin.getComfirmPassword(),"两次密码不一致");


        //1.2 店铺是否存在校验
        List<Tenant> tenants = tenantMapper.selectList(new EntityWrapper<Tenant>().eq("company_name", tenant.getCompanyName()));
        Assert.assertListIsEmpty(tenants,StatusCode.CODE_400_TENANT_EXIST);
        //1.3 管理员存在校验
        List<Employee> employees = employeeMapper.selectList(new EntityWrapper<Employee>().eq("username",admin.getUsername()));
        Assert.assertListIsEmpty(employees,StatusCode.CODE_400_TENANT_ADMIN_EXIST);
    }

//    @Override
////    @Transactional
////    public AjaxResult settlement(TenantEnterDto enterDto) {
//////        //1参数校验
//////        if (StringUtils.isEmpty(enterDto)){
//////            throw new RuntimeException("请输入相关信息后再进行操作");
//////        }
//////        if (StringUtils.isEmpty(enterDto.getAdmin())){
//////            throw new RuntimeException("请输入完整的信息后再操作");
//////        }
//////        if (StringUtils.isEmpty(enterDto.getTenant())){
//////            throw new RuntimeException("请输入完整的信息后在操作");
//////        }
//////        if (StringUtils.isEmpty(enterDto.getMealId())){
//////            throw new RuntimeException("请输入完整的信息后在操作");
//////        }
//////        if (StringUtils.isEmpty(enterDto.getAdmin().getPassword())){
//////            throw new RuntimeException("请输入密码");
//////        }
////        Employee admin = enterDto.getAdmin();
////        Tenant tenant = enterDto.getTenant();
////        Long mealId = enterDto.getMealId();
////        LoginUser loginUser = new LoginUser();
////        BeanUtils.copyProperties(admin,loginUser);
////        loginUser.setType(0);
////        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
////        if (!ajaxResult.isSuccess()){
////            return AjaxResult.me().setSuccess(false).setMessage(ajaxResult.getMessage());
////        }
////        //2.2保存店铺管理员
////        admin.setType(5);//机构管理员
////        //这里登录用户返回的自增id在另一个模块，这里拿不到,所以登录用户id存到resultObj里面，
////        //存的时候是Long,通过Object转换，拿出来就是Integer了
////        Long loginId = Long.valueOf(((Integer) ajaxResult.getResultObj()).longValue());
////        admin.setLoginId(loginId);
////        employeeMapper.insert(admin);
////
////        //2.3保存店铺
////        tenant.setState(0);//待审核
////        tenant.setAdminId(admin.getId());
////        tenantMapper.insert(tenant);
////
////        //2.4保存用户套餐中间表
////        Long tenantId = tenant.getId();
////        Map<String,Object> map = new HashMap<>();
////        map.put("mealId",mealId);
////        map.put("tenantId",tenantId);
////        map.put("state", 0);//未支付
////        tenantMapper.insertTenantMeal(map);
////        return AjaxResult.me();
////    }
}
